package com.woniu.houtai.utils;

import com.woniu.houtai.config.Converter;
import com.woniu.houtai.entity.Product;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;
import java.util.UUID;

public class LoadingPicture {
    private static final String pathName = "http://192.168.201.159:10002/";

    public String setPic(MultipartFile picture, Product products) {

        String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        String suffix = uuid.substring(0, 3);
        String prefix = Converter.toDate(new Date());
        String proPicCode = prefix + suffix;

        if (picture.isEmpty()) {
            return "fail";
        } else {
            String fileName = picture.getOriginalFilename().toUpperCase();
            String sqlFilename =pathName + proPicCode + "-" + fileName  ;
            String newFilename = proPicCode + "-" + fileName  ;
            products.setImgSrc(sqlFilename);
            File file = new File( "E://E/imgs/" + newFilename);
            try {
                BufferedInputStream inputStream = new BufferedInputStream(picture.getInputStream());
                BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
                IOUtils.copy(inputStream, outputStream);
                outputStream.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "ok";
        }
    }

}
